﻿/*=========================================
* Author: DJ
* Description: 线程交叉访问助手   
==========================================*/
using System;
using System.Collections.Generic;
using UnityEngine;

public class ThreadCrooseHelper : MonoBehaviour
{

    public static ThreadCrooseHelper Instance;

    private void Awake()
    {
        Instance = this;
    }

    class ActionIntem
    {
        public Action CurrentAct { get; set; }
        public DateTime DelayTime { get; set; }

        public ActionIntem(Action act, DateTime time)
        {
            CurrentAct = act;
            DelayTime = time;
        }
    }

    /// <summary>
    /// 方法列表
    /// </summary>
    List<ActionIntem> actionList = new List<ActionIntem>();

    private void Update()
    {
        lock (actionList)
        {
            for (int i = actionList.Count - 1; i >= 0; i--)
            {
                if (actionList[i].DelayTime <= DateTime.Now)
                {
                    actionList[i].CurrentAct.Invoke();
                    actionList.RemoveAt(i);
                }
            }
        }
    }

    /// <summary>
    /// 在主线程中执行的方法
    /// </summary>
    /// <param name="action">方法</param>
    /// <param name="dateTime">时间</param>
    public void ExecuteOnMainThread(Action action, float dateTime = 0)
    {
        lock (actionList)
        {
            ActionIntem actIntem = new ActionIntem(action, DateTime.Now.AddSeconds(dateTime));
            actionList.Add(actIntem);
        }
    }

}